package com.ml4ai.backend.web.sys;

import com.ml4ai.backend.dto.CrawlTaskDTO;
import com.ml4ai.backend.dto.TextDTO;
import com.ml4ai.backend.dto.base.BaseAuditDTO;
import com.ml4ai.backend.services.CrawlTaskService;
import com.ml4ai.backend.services.WebCatchService;
import com.ml4ai.backend.stack.webcollector.TaskManager;
import com.ml4ai.backend.utils.RestUtil;
import com.ml4ai.backend.web.util.MapSpec;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by leecheng on 2018/10/19.
 */
@RestController
@RequestMapping("/api/webPageCatch")
public class WebPageCatchComponentRest {

    @Autowired
    WebCatchService webCatchService;

    @Autowired
    CrawlTaskService crawlTaskService;

    @ApiOperation(value = "开始任务", httpMethod = "POST")
    @RequestMapping(value = "/create")
    public Object create(@RequestBody CrawlTaskDTO crawlTaskDTO) {
        CrawlTaskDTO crawlTask = crawlTaskService.findById(crawlTaskDTO.getId());
        List<String> seed = crawlTask.getSeeds().stream().map(TextDTO::getValue).collect(Collectors.toList());
        List<String> regexies = crawlTask.getRegex().stream().map(TextDTO::getValue).collect(Collectors.toList());
        String[] regexArray = regexies.toArray(new String[0]);
        return RestUtil.success(webCatchService.catchPage(crawlTask.getId().toString(), seed, regexArray));
    }

    @ApiOperation(value = "正在抓取列表", httpMethod = "POST")
    @RequestMapping(value = "/onDoList", method = RequestMethod.POST)
    public Object list() {
        return RestUtil.success(TaskManager.getInstance().filter(task -> task != null));
    }

    @ApiOperation(value = "所有任务", httpMethod = "POST")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object all() {
        CrawlTaskDTO crawlTask = CrawlTaskDTO.builder().build();
        crawlTask.setStatus("1");
        List<CrawlTaskDTO> crawlTasks = crawlTaskService.query(crawlTask);
        return RestUtil.success(crawlTasks.stream().map(MapSpec::mapCrawlTask).collect(Collectors.toList()));
    }

    @ApiOperation(value = "添加任务", httpMethod = "POST")
    @RequestMapping(value = "/save", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Object createSave(@RequestBody CrawlTaskDTO crawlTaskDTO) {
        crawlTaskDTO.setStatus("1");
        CrawlTaskDTO crawlTask = crawlTaskService.save(crawlTaskDTO);
        return RestUtil.success(crawlTask);
    }
}
